#! /usr/bin/env python3
import pymysql
import re
import sys

try:
    sys.stdout = open('/tmp/accounts.pppp', 'w')
    print("class localaccounts::accounts {")
    # conn=MySQLdb.connect(host='ccs.ihep.ac.cn',user='puppet',passwd='puppet;123',db='cluster',port=3306,cursorclass = MySQLdb.cursors.DictCursor)
    conn = pymysql.connect(host='ccs.ihep.ac.cn', user='read', passwd='read;010', db='cluster', port=3306)
    cur = conn.cursor()
    cur.execute(
        'select a.afsaccount,a.fullaccount,b.group2value,a.afsgroup22,a.homedirectory,a.afstype2,a.uid,a.islock,a.del_flag from afsuser as a,afsgroup2 as b where a.afsgroup2=b.group2id')
    # cur.execute('select a.afsaccount,a.fullaccount,b.group2value,a.afsgroup22,a.homedirectory,a.afstype2,a.uid from afsuser as a,afsgroup2 as b where a.afsgroup2=b.group2id and a.afsaccount!="fengf"')
    users = cur.fetchall()
    cur.execute("select group2id,group2name from afsgroup2 where islock='0'")
    groups = cur.fetchall()
    cur.execute("select group2value,group2name from afsgroup2 where islock='0'")
    groupid = cur.fetchall()
    pgroups = dict(groups)
    dgroupid = dict(groupid)

    supply_groups = {}

    # change a.homedirectory to system homedir
    with open("/tmp/user.txt", 'w', encoding='utf-8') as file:
        for r in users:
            if r[6] < 100000:
                if re.search(r'/afs', r[4], re.M | re.I):
                    uhome = r[4] + "/" + r[0][0] + "/" + r[0]
                else:
                    uhome = r[4] + "/" + r[0]
                # print uhome
                # print r
                # Get group list form a.afsgroup22

                ugrouplist = []
                if r[3].strip() != '':
                    ugroups = r[3].split(",")
                    for a in ugroups:
                        ugrouplist.append(pgroups.get(int(a)))
                if len(ugrouplist):
                    try:
                        ugrouplist.remove(dgroupid.get(r[2]))
                    except:
                        pass
                print("  user { '" + r[0] + "':")
                # if user id delete then set to delete
                if r[8] == '1':
                    print("    ensure      => 'absent',")
                else:
                    print("    ensure      => 'present',")
                    print("    comment     => '" + r[1] + "',")
                    print("    gid         => '" + r[2] + "',")
                    print("    home        => '" + uhome + "',")
                    # if user is locked then set shell to nologin
                    if r[7] == '1':
                        shell = "/sbin/nologin"
                        print("    shell       => '/sbin/nologin',")
                    else:
                        shell = "/bin/" + r[5]
                        print("    shell       => '/bin/" + r[5] + "',")
                    print("    uid         => '" + str(r[6]) + "',")
                    print("    membership  => inclusive,")
                    # if ugrouplist:
                    print("    groups      => " + str(ugrouplist) + ",")
                print("  }")

                for i in ugrouplist:
                    if i not in supply_groups:
                        supply_groups[i] = []
                    else:
                        supply_groups[i].append(r[0])
                user_info = r[0] + ":x:" + str(r[6]) + ":" + str(r[2]) + ":" + r[1] + ":" + uhome + ":" + shell
                file.write(user_info + "\n")
    with open("/tmp/group.txt", 'w', encoding='utf-8') as file:
        for r in groupid:
            group_info = ""
            gid = r[0]
            groupname = r[1]
            supply_group_info = ""
            if groupname in supply_groups:
                for i in supply_groups[groupname]:
                    supply_group_info = supply_group_info + i + ","
                supply_group_info = supply_group_info.rstrip(",")
            group_info = groupname + ":x:" + gid + ":" + supply_group_info
            file.write(group_info + "\n")
            print("  group { '" + r[1] + "':")
            print("    ensure     => 'present',")
            print("    allowdupe  => true,")
            print("    gid     => '" + r[0] + "',")
            print("  }")
        print("}")
    cur.close()
    conn.close()
    sys.stdout.close()
except:
    print("Mysql Error %d: %s" % (e.args[0], e.args[1]))
    sys.exit(1)

